package cz.tpj.upl;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cz.tpj.logic.Navigation;
import cz.tpj.util.ErrorClass;
import cz.tpj.util.ErrorDatabase;

/**
 * Servlet implementation class upload
 */
public class Upload extends HttpServlet {
		
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream out = response.getOutputStream();
		out.println("Neznamy pristup!!!");
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		String message = new String();
		
		//nacte zpet drive nastavene parametry
		AddCityUtil adu = new AddCityUtil(request);
		adu.fetchParametrs();
		adu.saveAtributsAndParametrs();
		//presmerovani zpet na JSP pridej mesto
	    String nextJSP = Navigation.JSP_INSERT_CITY_PICTURES;
		try {
			//nacteni dat do tempu
			MediaFolder mf = MediaFolder.getInstance();
			mf.uploadFile(request, response);
			//presunuti dat do slozky media/cities/"id mesta"
			if(session.getAttribute(AddCityUtil.CITY_ID) == null){
				message = "<p>Přístupné pouze po vložení nového města!</p>";
			}
			String cityID = (String) session.getAttribute(AddCityUtil.CITY_ID);
			message = mf.moveImagesInMediaFolder(cityID);
			//zprava o vysledku ukladani
			
			message += "<p>Data Byla uspesne ulozena</p>";
			nextJSP = Navigation.JSP_CULTURAL_INTERESTS;
			//vynulovani session
			session.setAttribute(AddCityUtil.CITY_NAME, null);
			session.setAttribute(AddCityUtil.CITY_ID, 	null);
			session.setAttribute(AddCityUtil.NEXT_PAGE, null);
			session.setAttribute(AddCityUtil.LONG_DESC, null);
			session.setAttribute(AddCityUtil.MAP_NAME, 	null);
			session.setAttribute(AddCityUtil.SHORT_DESC,null);
			
		} catch (ErrorClass e) {
			message = "<p>chyba pro ukladani dat</p>";
		} catch (ErrorDatabase e) {
			message = "<p>chyba pro ukladani dat</p>";
		}
		
		
	    //nastaveni oznamovaci zpravy do session
		
		session.setAttribute(Navigation.SESIION_MESSAGE, message);
	    
	    //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(""+nextJSP);
	    //dispatcher.forward(request,response);
		response.sendRedirect(nextJSP);
	}
	
	
	
	
	
}
